//
//  FAI.m
//  ui
//
//  Created by 袁飞 on 12-7-19.
//
//

#import "FishAI.h"
#import "FObject.h"
#import "FUtil.h"
#import "FishManager.h"
#import "Player.h"

@implementation FishAI 
-(id)initWithFObject:(FObject*)obj{
  [super init];
  object_ = obj;
  [[CCScheduler sharedScheduler] scheduleSelector:@selector(onTimer) forTarget:self interval:0.1f paused:false];
  return self;
}

-(void)onMoveEnd{
  [object_ stopAllActionWithSprite:@"normal"];
  CGPoint begin = [object_ position];
  
  float x = rand()%(460-120)+120;

  //CCSprite* sp = [object_ getSpriteByName:@"normal"];
  //bool isflip = sp.flipX;
  
  //if (x < begin.x && !isflip) {
  //  [object_ runAction:@"turn" WithSprite:@"normal" Dur:1.0];
  //}else if (x > begin.x && isflip) {
  //  [object_ runAction:@"turn" WithSprite:@"normal" Dur:1.0];
  //}else{
    [self randomMove];
  //}
}

-(void)onActionEnd:(id)sender Data:(NSString*)data{
  if([data compare:@"turn"] == NSOrderedSame){
    CCSprite* sp = [object_ getSpriteByName:@"normal"];
    bool isflip = sp.flipX;
    [sp setFlipX:!isflip];
    [self randomMove];
  }
}

-(void)start{
  //float x = rand()%(460-120)+120;
  //float y = rand()%(300-20)+20;
  //[object_ setPosition:ccp(x,y)];
  
  int direction = rand()%2;
  if (direction == 1) {
   bool flip = [[object_ getSpriteByName:@"normal"] flipX];
   [[object_ getSpriteByName:@"normal"] setFlipX:!flip];
  }
  [self randomMove];
}

-(void)randomMove{
  CGPoint begin = [object_ position];
  CCSprite* sp = [object_ getSpriteByName:@"normal"];
  bool isflip = sp.flipX;

  float x = rand()%200+120;
  int dir = rand()%10;
  if (dir>5) {
    x *= -1;
  }
  if (x>0) {
    [sp setFlipX:true];
  }else {
    [sp setFlipX:false];
  }
  /*float y = rand()%(300-20)+20;
  if (isflip) {
    x = rand()%((int)begin.x+1) + 120;
    y = rand()%(300-20)+20;
  }else{
    x = rand()%(460 - (int)begin.x) + begin.x;
    y = rand()%(300-20)+20;
  }*/
  CGPoint end = ccp(x, begin.y);
  float speed = [[(FishData*)object_ config] speed];
  //rand()%100;
  float dur = ccpDistance(begin, ccp(begin.x+x, begin.y))/speed;
  
  [object_ moveBy:ccp(x, 0) Dur:dur];
  //[object_ runActionRepeated:@"move" WithSprite:@"normal"];
}

-(void)onTimer{
  FishData* fd = (FishData*)object_;
  Player *pl = [Player sharedPlayer];
  CGPoint pp = [pl position];
  CGPoint fp = [fd getLocalPosition];
  float distance = ccpDistanceSQ(pp, fp);
  if(distance > [fd vision]*[fd vision]){
    return;
  } 
  
  [object_ stopAllAction];
  
  bool needflip = true;
  float move_distance = 3.0*[[fd config] speed];
  if(pp.x > fp.x){
    needflip = false;
    move_distance *= -1;
  }
  
  CCSprite* sp = [object_ getSpriteByName:@"normal"];
  bool isflip = sp.flipX;
  if(needflip != isflip){
    [sp setFlipX:needflip];
  }
  [object_ moveBy:ccp(move_distance, 0) Dur:1.0];
  //[object_ runActionRepeated:@"move" WithSprite:@"normal"];
}
@end
